package com.zlc.big_event.controller;


import com.zlc.big_event.pojo.Result;
import com.zlc.big_event.pojo.User;
import com.zlc.big_event.service.UserService;
import com.zlc.big_event.utils.JwtUtil;
import com.zlc.big_event.utils.Md5Util;
import com.zlc.big_event.utils.ThreadLocalUtil;
import io.micrometer.common.util.StringUtils;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserCotroller {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //注册
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^[a-zA-Z0-9_-]{3,16}$",message = "用户名格式不正确") String username,@Pattern(regexp = "^[a-zA-Z0-9_-]{3,16}$",message = "用户名格式不正确") String password){
        //查询用户名是否已存在
        User u = userService.findByUsername(username);
        if(u==null){
            //没有占用
            //注册
            userService.register(username,password);
            return  Result.success();
        }else{
            //占用
            return Result.error("用户名已占用");
        }
    }

    // 登录接口
    @PostMapping("/login")
    public Result login(
        @Pattern(regexp = "^[a-zA-Z0-9_-]{3,16}$", message = "用户名格式不正确") String username,
        @Pattern(regexp = "^[a-zA-Z0-9_-]{3,16}$", message = "用户名格式不正确") String password) {
        // 根据用户名查询用户信息
        User u = userService.findByUsername(username);
        if (u == null) {
            // 用户名不存在时返回错误信息
            return Result.error("用户名不存在");
        }
        // 验证密码是否正确
        if (Md5Util.getMD5String(password).equals(u.getPassword())) {
            // 登录成功，生成令牌（Token）
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", u.getId());
            claims.put("username", u.getUsername());
            String token = JwtUtil.genToken(claims);

            // 将Token存储到Redis中，设置过期时间为1小时
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 1, TimeUnit.HOURS);

            // 返回登录结果及Token
            return Result.success(token);
        }
        // 密码错误时返回错误信息
        return Result.error("密码错误");
    }

    //获取用户信息
    @GetMapping( "/userInfo")
    public Result<User> userInfo(@RequestHeader(name="Authorization") String token){
        // 从ThreadLocal中获取之前存储的用户信息
        Map<String,Object> map = ThreadLocalUtil.get();
        // 从map中获取用户名
        String username =(String) map.get("username");
        // 根据用户名查询用户信息
        User user = userService.findByUsername(username);
        // 返回查询到的用户信息
        return Result.success(user);
    }

    //修改用户信息
    @PutMapping( "/update")
    public Result update(@RequestBody @Validated  User user) {
        userService.update(user);
        return Result.success();
    }

    //修改用户头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatar){
        //修改用户头像
        userService.updateAvatar(avatar);
        return Result.success();
    }

    //修改密码
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String ,String> params,@RequestHeader("Authorization") String token){
        //从参数中获取旧密码、新密码和确认密码
        String oldPwd =params.get("oldpassword");
        String newPwd =params.get("newpassword");
        String rePwd  =params.get("repassword");

        //检查密码参数是否为空
        if (StringUtils.isEmpty(oldPwd)||StringUtils.isEmpty(newPwd)||StringUtils.isEmpty(rePwd))
            return Result.error("参数不能为空");

        //从线程局部变量中获取当前用户信息
        Map<String,Object> map = ThreadLocalUtil.get();
        String username =(String) map.get("username");

        //根据用户名查找登录用户
        User loginUser = userService.findByUsername(username);

        //验证旧密码是否正确
        if(!Md5Util.getMD5String(oldPwd).equals(loginUser.getPassword()))
            return Result.error("旧密码不正确");

        //验证新密码和确认密码是否一致
        if(!newPwd.equals(rePwd))
            return Result.error("两次密码不一致");

        //更新用户密码
        userService.updatePwd(newPwd);

        //删除旧的登录令牌
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);

        //返回成功结果
        return Result.success();
    }




}
